﻿using Common.Enums;
using Common.Exceptions;
using Common.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Wallpaper.Data.Context;
using Wallpaper.Data.IDal;
using Wallpaper.Models.DTOs.Requests.Wallpaper;
using Wallpaper.Models.DTOs.Requests.WallPaper;
using Wallpaper.Models.DTOs.Responses.Tag;
using Wallpaper.Models.DTOs.Responses.Wallpaper;
using Wallpaper.Models.Entities;
using Wallpaper.Services.IService;

namespace Wallpaper.Services.Service
{
    public class WallpaperService : IWallpaperService
    {

        readonly IWallpaperDal _wallpaperDal;
        readonly IMinioService _minioService;
        readonly WallpaperDbContext _dbContext;
        readonly ILogger<WallpaperService> _logger;
        readonly IUserDal _userDal;
        readonly IMessageService _messageService;
            

        public WallpaperService(IWallpaperDal wallpaperDal, IMinioService minioService, WallpaperDbContext dbContext, ILogger<WallpaperService> logger, IUserDal userDal,  IMessageService messageService)
        {
            _wallpaperDal = wallpaperDal;
            _minioService = minioService;
            _dbContext = dbContext;
            _logger = logger;
            _userDal = userDal;
            _messageService = messageService;
        }



        /// <summary>
        /// 删除壁纸
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            Wallpapers wallpaper = await _wallpaperDal.GetByIdAsync(id);
            if (wallpaper == null)
            {
                throw new DataNotFoundException("壁纸不存在,或数据异常");
            }

            // MinIO 删除成功后，删除数据库记录
            bool dbResult = await _wallpaperDal.DeleteByIdAsync(id);
            return dbResult;
        }


        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagedResult<WallpaperPageResponse>> PageAsync(WallpaperQueryRequest request)
        {
            var query = _wallpaperDal.GetQueryable();

            if (!string.IsNullOrWhiteSpace(request.Title))
            {
                query = query.Where(w => w.Title.Contains(request.Title));
            }
            if (!string.IsNullOrWhiteSpace(request.CategoryId))
            {
                query = query.Where(w => w.CategoryId == request.CategoryId);
            }

            // 审核状态筛选
            if (request.ReviewStatus.HasValue)
            {
                query = query.Where(w => w.ReviewStatus == request.ReviewStatus.Value);
            }


            // 审核状态筛选
            if (request.IsEnabled.HasValue)
            {
                query = query.Where(w => w.IsEnabled == request.IsEnabled);
            }
            // 时间范围筛选
            if (request.StartTime.HasValue)
            {
                query = query.Where(w => w.CreatedAt >= request.StartTime.Value);
            }
            if (request.EndTime.HasValue)
            {
                query = query.Where(w => w.CreatedAt <= request.EndTime.Value);
            }

            // 获取总数
            var totalCount = await query.CountAsync();

            var items = await query
                    .OrderByDescending(w => w.CreatedAt)
                    .Skip((request.Page - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .Select(w => new WallpaperPageResponse
                    {
                        Id = w.Id,
                        CategoryId = w.CategoryId,
                        Title = w.Title,
                        CategoryName = w.Category.Name,
                        FileUrl = w.FileUrl,
                        ReviewComment = w.ReviewComment,
                        ReviewStatus = w.ReviewStatus,
                        UploaderType = w.UploaderType, // 修正这里
                        IsEnabled = w.IsEnabled,
                        ReviewedTime = w.ReviewedAt,
                        CreatedTime = w.CreatedAt,
                        // 直接从 WallpaperTags 导航属性获取 Tags
                        Tags = w.WallpaperTags
                            .Where(wt => wt.Tag != null) // 确保 Tag 不为空
                            .Select(wt => new TagResponse
                            {
                                Id = wt.Tag.Id,
                                Name = wt.Tag.Name,
                            }).ToList(),
                        UploaderName = w.UploaderType == UploaderType.NormalUser
                            ? _dbContext.Users.Where(u => u.Id == w.UploaderId).Select(u => u.Nickname).FirstOrDefault()
                            : w.UploaderType == UploaderType.Admin
                                ? _dbContext.Admins.Where(a => a.Id == w.UploaderId).Select(a => a.Account).FirstOrDefault()
                                : "系统",
                        ReviewerName = w.ReviewerId != null
                            ? _dbContext.Admins.Where(a => a.Id == w.ReviewerId).Select(a => a.Account).FirstOrDefault()
                            : null
                    })
                    .ToListAsync();
            return new PagedResult<WallpaperPageResponse>
            {
                Page = request.Page,
                PageSize = request.PageSize,
                TotalCount = totalCount,
                Items = items
            };


        }


        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> UpdatedWallpaperAsync(string id, UpdateWallpaperRequest request)
        {
            if (id == null)
            {
                throw new ArgumentNullException("壁纸id不能为空", nameof(id));
            }
            if (request.FileUrl == null)
            {
                throw new ArgumentNullException("壁纸不能为空", nameof(request.FileUrl));
            }

            var wallpapers = await _wallpaperDal.GetByIdAsync(id);
            if (wallpapers == null)
            {
                throw new BusinessException("壁纸不存在或已被删除", 404);
            }

            // 保存旧文件路径，用于后续删除
            string oldFileUrl = wallpapers.FileUrl;
            bool shouldDeleteOldFile = oldFileUrl != request.FileUrl;

            using var transaction = await _dbContext.Database.BeginTransactionAsync();
            try
            {
                // 1. 先删除该壁纸的所有标签关联
                var existingTags = _dbContext.Set<WallpaperTag>()
                    .Where(wt => wt.WallpaperId == id);
                _dbContext.Set<WallpaperTag>().RemoveRange(existingTags);

                // 2. 更新壁纸基本信息
                wallpapers.Title = request.Title;
                wallpapers.FileUrl = request.FileUrl;
                wallpapers.CategoryId = request.CategoryId;
                wallpapers.IsEnabled = request.IsEnabled;
                wallpapers.UpdatedAt = DateTime.Now;

                // 3. 添加新的标签关联
                if (request.Tags != null && request.Tags.Any())
                {
                    var newWallpaperTags = request.Tags.Select(tagId => new WallpaperTag
                    {
                        Id = Guid.NewGuid().ToString(),
                        WallpaperId = id,
                        TagId = tagId
                    }).ToList();

                    await _dbContext.Set<WallpaperTag>().AddRangeAsync(newWallpaperTags);
                    await UpdateTagsUsageCount(request.Tags);
                }

                // 4. 保存所有更改
                await _dbContext.SaveChangesAsync();
                await transaction.CommitAsync();

                // 5. 事务提交成功后，再删除旧文件
                if (shouldDeleteOldFile && !string.IsNullOrEmpty(oldFileUrl))
                {
                    try
                    {
                        await _minioService.RemoveFileAsync(oldFileUrl);
                    }
                    catch (Exception ex)
                    {
                        // 文件删除失败不影响主业务，记录日志即可
                        _logger.LogWarning(ex, "删除旧文件失败: {FileUrl}", oldFileUrl);
                    }
                }

                return true;
            }
            catch
            {
                await transaction.RollbackAsync();
                throw;
            }
        }


        /// <summary>
        /// 上传壁纸
        /// </summary>
        /// <param name="upload"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> UploadWallpaperAsync(UploadWallpaperRequest upload, string adminId)
        {
            ValidateUploadRequest(upload, adminId);

            using var transaction = await _dbContext.Database.BeginTransactionAsync();
            try
            {
                // 创建壁纸实体
                var wallpaper = new Wallpapers
                {
                    Id = Guid.NewGuid().ToString(),
                    UploaderId = adminId,
                    Title = upload.Title.Trim(),
                    CategoryId = upload.CategoryId,
                    FileUrl = upload.FileUrl,
                    UploaderType = (UploaderType)1,
                    ReviewStatus = GetReviewStatus((UploaderType)1),
                    ReviewComment = "后台上传自动通过",
                    ReviewerId = adminId,
                    Height = upload.Height ?? 0,
                    Width = upload.Width ?? 0,
                    IsEnabled = upload.IsEnabled,
                    ReviewedAt = DateTime.Now
                };

                // 使用同一个 DbContext
                await _dbContext.Set<Wallpapers>().AddAsync(wallpaper);

                // 创建 tags 关联
                if (upload.Tags != null && upload.Tags.Any())
                {
                    await CreateWallpaperTagsAsync(wallpaper.Id, upload.Tags);
                    await UpdateTagsUsageCount(upload.Tags);
                }

                // 一次性保存所有更改
                var result = await _dbContext.SaveChangesAsync() > 0;

                await transaction.CommitAsync();
                return result;
            }
            catch
            {
                await transaction.RollbackAsync();
                throw;
            }
        }

        /// <summary>
        /// 创建TagWallpaper
        /// </summary>
        /// <param name="wallpaperId"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        private async Task CreateWallpaperTagsAsync(string wallpaperId, List<string> tags)
        {
            var wallpaperTags = tags.Select(tag => new WallpaperTag
            {
                Id = Guid.NewGuid().ToString(),
                WallpaperId = wallpaperId,
                TagId = tag
            }).ToList();

            await _dbContext.Set<WallpaperTag>().AddRangeAsync(wallpaperTags);
        }

        /// <summary>
        /// 更新tags次数
        /// </summary>
        /// <param name="tagIds"></param>
        /// <returns></returns>
        private async Task UpdateTagsUsageCount(List<string> tagIds)
        {
            // 1. 先查询出所有存在的标签
            var existingTags = await _dbContext.Set<Tags>()
                .Where(t => tagIds.Contains(t.Id))
                .ToListAsync();

            // 2. 更新每个标签的使用次数
            foreach (var tag in existingTags)
            {
                tag.UsageCount = tag.UsageCount + 1;
                tag.UpdatedAt = DateTime.Now;
            }
        }




        /// <summary>
        /// 根据上传者类型确定审核状态
        /// </summary>
        private WallpaperReviewStatus GetReviewStatus(UploaderType uploaderType)
        {
            return uploaderType switch
            {
                UploaderType.NormalUser => WallpaperReviewStatus.Pending,     // 普通用户需要审核
                UploaderType.Admin => WallpaperReviewStatus.Approved,         // 管理员自动通过      
                UploaderType.System => WallpaperReviewStatus.Approved,        // 系统自动通过
                _ => WallpaperReviewStatus.Pending                            // 默认需要审核
            };
        }



        /// <summary>
        /// 验证上传请求参数
        /// </summary>
        private void ValidateUploadRequest(UploadWallpaperRequest upload, string userId)
        {
            if (upload == null)
                throw new ArgumentNullException(nameof(upload));

            if (string.IsNullOrWhiteSpace(userId))
                throw new ArgumentException("ID不能为空", nameof(userId));

            if (string.IsNullOrWhiteSpace(upload.Title))
                throw new BusinessException("壁纸标题不能为空");

            if (string.IsNullOrWhiteSpace(upload.FileUrl))
                throw new BusinessException("文件URL不能为空");
        }

        /// <summary>
        /// 小程序搜索
        /// </summary>
        /// <param name="searchRequest"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagedResult<QueryWallpaperResponse>> SearchWallpapersAsync(SearchRequest searchRequest)
        {
            var query= _wallpaperDal.GetQueryable().Where(w => w.IsEnabled && !w.IsDeleted&&w.ReviewStatus== WallpaperReviewStatus.Approved);

            //分类搜索
            if (!string.IsNullOrEmpty(searchRequest.CategoryId))
            {
                query = query.Where(w => w.CategoryId == searchRequest.CategoryId);
            }

            // 分类搜索 - 修正了条件判断
            if (!string.IsNullOrEmpty(searchRequest.CategoryId))
            {
                query = query.Where(w => w.CategoryId == searchRequest.CategoryId);
            }

            // 关键词搜索（搜索标题或标签）
            if (!string.IsNullOrWhiteSpace(searchRequest.KeyWord))
            {
                /*
                 SELECT w.*
                        FROM Wallpapers w
                        WHERE w.IsEnabled = 1 
                          AND w.IsDeleted = 0
                          AND (
                            w.Title LIKE '%关键词%' 
                            OR EXISTS (
                              SELECT 1 
                              FROM wallpaper_tags wt 
                              INNER JOIN Tags t ON wt.TagId = t.Id 
                              WHERE wt.WallpaperId = w.Id 
                                AND t.Name LIKE '%关键词%'
                            )
                          )
                 */
                query = query.Where(w =>
                    w.Title.Contains(searchRequest.KeyWord) ||  // 搜索标题
                    w.WallpaperTags.Any(wt => wt.Tag.Name.Contains(searchRequest.KeyWord))  // 搜索标签名称
                );
            }
            var totalCount = await query.CountAsync();

            List<QueryWallpaperResponse> items = await query
                    .OrderByDescending(w => w.ReviewedAt)
                    .Skip((searchRequest.Page - 1) * searchRequest.PageSize)
                    .Take(searchRequest.PageSize)
                    .Select(w => new QueryWallpaperResponse
                    {
                        Id = w.Id,
                        FileUrl = w.FileUrl,
                        Title = w.Title
                    }).ToListAsync();
            return new PagedResult<QueryWallpaperResponse>
            {
                Page = searchRequest.Page,
                PageSize = searchRequest.PageSize,
                TotalCount = totalCount,
                Items = items
            };
        }


        /// <summary>
        /// 小程序首页壁纸
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagedResult<WallpapersResponse>> IndexAsync(PageRequest request)
        {
            // 先获取总数
            var totalCount = await _wallpaperDal.GetQueryable()
                .Where(w => w.IsEnabled && !w.IsDeleted&&w.ReviewStatus== WallpaperReviewStatus.Approved)
                .CountAsync();

            // 再获取分页数据
            var wallpapers = await _wallpaperDal.GetQueryable()
                .Where(w => w.IsEnabled && !w.IsDeleted)
                .OrderByDescending(w => w.ReviewedAt)
                .Skip((request.Page - 1) * request.PageSize) //跳过前面多少条记录
                .Take(request.PageSize) //获取多少条记录
                .Select(w => new WallpapersResponse
                {
                    Id = w.Id,
                    FileUrl = w.FileUrl
                })
                .ToListAsync();
            return new PagedResult<WallpapersResponse>
            {
                Page = request.Page,
                PageSize = request.PageSize,
                TotalCount = totalCount,
                Items = wallpapers
            };
        }

        /// <summary>
        /// 小程序壁纸上传
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// <summary>
        /// 应用上传壁纸
        /// </summary>
        /// <param name="request">上传请求参数</param>
        /// <param name="userId">用户ID</param>
        /// <returns>上传是否成功</returns>
        public async Task<bool> AppUploadWallpaperAsync(AppUploadWallpaperRequest request, string userId)
        {
            // 验证上传请求参数
            ValidateUploadRequest(request, userId);

            // 开始数据库事务，确保数据一致性
            using var transaction = await _dbContext.Database.BeginTransactionAsync();
            try
            {
                // 创建壁纸实体
                var wallpaper = new Wallpapers
                {
                    Id = Guid.NewGuid().ToString(),
                    UploaderId = userId,                    // 上传用户ID
                    CategoryId = request.CategoryId,        // 分类ID
                    FileUrl = request.FileUrl,              // 文件URL地址
                    Title = request.Title,                  // 壁纸标题
                    UploaderType = (UploaderType)0,         // 上传人类型：用户
                    ReviewStatus = GetReviewStatus((UploaderType)0), // 根据上传类型获取审核状态
                    ReviewerId = "",                        // 审核人ID（初始为空）
                    Height = 0,                             // 图片高度（后续可更新）
                    Width = 0,                              // 图片宽度（后续可更新）
                    IsEnabled = true,                       // 启用状态
                };

                // 添加壁纸到数据库
                await _dbContext.Set<Wallpapers>().AddAsync(wallpaper);

                // 创建或关联标签
                await CreateTags(wallpaper.Id, request.Tags);

                // 统一保存所有数据库更改（壁纸 + 标签 + 关联关系）
                var result = await _dbContext.SaveChangesAsync() > 0;

                // 提交事务
                await transaction.CommitAsync();

                return result;
            }
            catch
            {
                // 发生异常时回滚事务
                await transaction.RollbackAsync();
                throw; // 重新抛出异常
            }
        }

        /// <summary>
        /// 创建或绑定标签到壁纸
        /// 处理逻辑：
        /// 1. 检查标签是否已存在
        /// 2. 创建不存在的标签
        /// 3. 建立壁纸与标签的关联关系
        /// </summary>
        /// <param name="wallpaperId">壁纸ID</param>
        /// <param name="tags">标签名称列表</param>
        public async Task CreateTags(string wallpaperId, List<string> tags)
        {
            // 检查标签列表是否为空
            if (tags == null || !tags.Any()) return;

            // 对标签进行去重处理
            var distinctTags = tags.Distinct().ToList();

            // 批量检查已存在的标签
            var existingTags = await _dbContext.Set<Tags>()
                .Where(t => distinctTags.Contains(t.Name) && !t.IsDeleted)
                .ToListAsync();

            // 获取已存在标签的名称列表
            var existingTagNames = existingTags.Select(t => t.Name).ToList();

            // 找出需要新增的标签（排除已存在的）
            var newTagNames = distinctTags.Except(existingTagNames).ToList();

            // 批量创建新标签
            var newTags = newTagNames.Select(tagName => new Tags
            {
                Id = Guid.NewGuid().ToString(),     
                Name = tagName,                                  
                IsDeleted = false                   
            }).ToList();

            // 如果有新标签，批量添加到数据库
            if (newTags.Any())
            {
                await _dbContext.Set<Tags>().AddRangeAsync(newTags);
            }

            // 合并所有标签（已存在的 + 新创建的）
            var allTags = existingTags.Concat(newTags).ToList();

            // 批量创建壁纸-标签关联关系
            var wallpaperTags = allTags.Select(tag => new WallpaperTag
            {
                Id = Guid.NewGuid().ToString(),    
                WallpaperId = wallpaperId,          
                TagId = tag.Id                    
            }).ToList();

            // 批量添加关联关系到数据库
            await _dbContext.Set<WallpaperTag>().AddRangeAsync(wallpaperTags);

            // 这里不调用 SaveChangesAsync()，由外层统一保存 确保在同一个事务中完成所有数据库操作
            
        }

        /// <summary>
        /// 上传验证
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userId"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="BusinessException"></exception>
        private void ValidateUploadRequest(AppUploadWallpaperRequest request, string userId)
        {
            if (request == null)
                throw new ArgumentNullException(nameof(request));

            if (string.IsNullOrWhiteSpace(userId))
                throw new ArgumentException("ID不能为空", nameof(userId));

            if (string.IsNullOrWhiteSpace(request.Title))
                throw new BusinessException("壁纸标题不能为空");

            if (string.IsNullOrWhiteSpace(request.FileUrl))
                throw new BusinessException("文件URL不能为空");
        }


        /// <summary>
        /// 后台审核小程序壁纸
        /// </summary>
        /// <param name="wallpaperId"></param>
        /// <param name="adminId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task ReviewUserWallpaperAsync(string id, string adminId, ReviewWallpaperRequest request)
        {
            // 参数验证
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentException("壁纸ID不能为空", nameof(id));
            }
            if (string.IsNullOrWhiteSpace(adminId))
            {
                throw new ArgumentException("审核人不能为空", nameof(adminId));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request), "审核信息不能为空");
            }

            // 获取壁纸实体
            var wallpaper = await _wallpaperDal.GetByIdAsync(id);
            if (wallpaper == null)
            {
                throw new BusinessException($"未找到ID为 {id} 的壁纸",404);
            }

            //// 验证审核状态是否有效
            if (!Enum.IsDefined(typeof(WallpaperReviewStatus), request.ReviewStatus))
            {
                throw new ArgumentException("无效的审核状态", nameof(request.ReviewStatus));
            }

            // 更新审核信息
            wallpaper.ReviewStatus = request.ReviewStatus;
            wallpaper.ReviewerId = adminId;
            wallpaper.ReviewedAt = DateTime.Now;

            // 如果有审核意见，也更新
            if (!string.IsNullOrWhiteSpace(request.ReviewComment))
            {
                wallpaper.ReviewComment = request.ReviewComment;
            }

            await _wallpaperDal.UpdateEntityAsync(wallpaper);
            await _messageService.SendReviewNotificationAsync(wallpaper.UploaderId, wallpaper.Id, wallpaper.Title, request.ReviewStatus, request.ReviewComment);

        }




        /// <summary>
        /// 获取用户上传壁纸
        /// </summary>
        /// <param name="reviewStatus"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagedResult<QueryWallpaperResponse>> GetWallpapersAsync(int reviewStatus, string UserId, int page, int pageSize)
        {
            var status = (WallpaperReviewStatus)reviewStatus;
            var query= _wallpaperDal.GetQueryable().Where(w => w.IsEnabled && !w.IsDeleted && w.ReviewStatus == status&&w.UploaderId==UserId);
            var totalCount = await _wallpaperDal.GetQueryable()
    .Where(w => w.IsEnabled && !w.IsDeleted && w.ReviewStatus == WallpaperReviewStatus.Approved)
    .CountAsync();


          var wallpapers= await query.OrderByDescending(w => w.ReviewedAt)
            .Skip((page - 1) * pageSize) //跳过前面多少条记录
            .Take(pageSize) //获取多少条记录
                .Select(w => new QueryWallpaperResponse
                {
                    Id = w.Id,
                    Title=w.Title,
                    FileUrl = w.FileUrl
                })
                .ToListAsync();
            return new PagedResult<QueryWallpaperResponse>
            {
                Page = page,
                PageSize = pageSize,
                TotalCount = totalCount,
                Items = wallpapers
            };
        }


        /// <summary>
        /// 根据id获取壁纸详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<DetailResponse> GetWallpaperDetailAsync(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException(nameof(id), "壁纸id不能为空");
            }

            // 获取壁纸信息（包含分类和标签）
            var wallpaper = await _wallpaperDal.GetQueryable()
                .Include(w => w.Category) // 第1步：加载分类信息
                .Include(w => w.WallpaperTags)  // 第2步：加载中间表关系
                    .ThenInclude(wt => wt.Tag) // 第3步：通过中间表加载标签详情
                .FirstOrDefaultAsync(w => w.Id == id); // 第4步：执行查询

            if (wallpaper == null)
            {
                throw new BusinessException($"ID为{id}的壁纸不存在或数据异常", 404);
            }

            // 单独查询用户信息
            User uploader = null;
            if (!string.IsNullOrEmpty(wallpaper.UploaderId))
            {
                uploader = await _userDal.GetByIdAsync(wallpaper.UploaderId);
              
            }

            // 映射到响应对象
            return new DetailResponse
            {
                Id = wallpaper.Id,
                Title = wallpaper.Title,
                Tags =  wallpaper.WallpaperTags.Select(wt => wt.Tag?.Name).Where(name => !string.IsNullOrEmpty(name)).ToList(),
                UploadName = uploader?.Nickname ?? "后台上传",
                Avatar = uploader?.AvatarUrl ?? "",
                FileUrl = wallpaper.FileUrl,
                CategoryName = wallpaper.Category?.Name ?? "未分类"
            };
        }


        
       
    }
}
